
/*
 * @Author: WLang
 * @LastEditors: WLang
 * @Description: 
 * @Date: 2023-07-09 12:45:24
 * @LastEditTime: 2023-07-18 23:39:29
 * @FilePath: \myblog\src\store\modules\like.js
 */
import store from 'store'
import base from '@/config/base.config'
import Vue from 'vue'
const {LIKE_NAME} = base
export default {
  namespaced: true,
  state: {
    likes: store.get(LIKE_NAME) || []
  },
  getters: {
    //是否存在点赞
    isLike: state=>(aid) => {
      return !!(state.likes.includes(aid))
    }
  },
  mutations: {
    //修改点赞用户
    CHANGE_LIKE(state)
    {
      state.likes = store.get(LIKE_NAME)
    }
  },
  actions: {
    //点赞
    pushLike({commit}, payload)
  {
    let {aid} = payload
    if (aid)
  {
    let locallLikes = store.get(LIKE_NAME) || []
    let idx = locallLikes.indexOf(aid)
    if (idx === -1)
    {
      locallLikes.push(aid)
    }
    store.set(LIKE_NAME, locallLikes)
    commit('CHANGE_LIKE')
  }
  },
  //取消点赞
  pullLike({commit}, payload) {
    let {aid} = payload
    if (aid)
    {
      let locallLikes = store.get(LIKE_NAME) || []
      let idx = locallLikes.indexOf(aid)
      if (idx !== -1)
      {
        locallLikes.splice(idx, 1)
      }
      store.set(LIKE_NAME, locallLikes)
      commit('CHANGE_LIKE')
    }
    },
    //发送点赞请求
    async sendLikes({state},{aid}) {
        await Vue.prototype.$api({type: 'addArticleLikes', data: {id: aid}})
    }
  }
}